package com.sanyuan.cloud.module.system.aop;

import com.sanyuan.cloud.module.system.dal.dataobject.nongmo.SystemPositionDO;
import com.sanyuan.cloud.module.system.service.nongmo.impl.GeoSyncService;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description: 数据同步监听（保证MySQL和Redis一致性）
 * @Author: wuyuwei
 * @Date: 2025/3/28
 */
@Aspect
@Component
@RequiredArgsConstructor
public class PositionDataSyncAspect {
    private final GeoSyncService geoSyncService;

    @AfterReturning(pointcut = "execution(* com.sanyuan.cloud.module.system.dal.mysql.nongmo.SystemPositionMapper.insertEntity(..))", returning = "result")
    public void afterInsert(SystemPositionDO result) {
        geoSyncService.addToRedis(result);
    }

    @AfterReturning(pointcut = "execution(* com.sanyuan.cloud.module.system.dal.mysql.nongmo.SystemPositionMapper.updateById(..))", returning = "result")
    public void afterUpdate(SystemPositionDO result) {
        if (Objects.isNull(result)){
            return;
        }
        if (result.getDeleted()) {
            geoSyncService.removeFromRedis(result.getId());
        } else {
            geoSyncService.addToRedis(result);
        }
    }

    @AfterReturning("execution(* com.sanyuan.cloud.module.system.service.nongmo.impl.SystemPositionServiceImpl.deleteById(..)) && args(id)")
    public void afterDelete(Long id) {
        geoSyncService.removeFromRedis(id);
    }
}